<template>
  <section class="modlude">
    <el-form :inline="true" ref="formSearch" :model="formSearch" class="form_inline" label-width="90px">
      <el-form-item label="所属组织" size="small">
        <el-cascader ref="cascader" v-model="option1" :options="dataTree" :props="defaultProps2" @change="handleChange"
          clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="所属项目" size="small">
        <el-select v-model="formSearch.projectId" placeholder="请选择项目">
          <el-option v-for="(item,index) in xqTree" :label="item.name" :value="item.id" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="检查项名称" size="small">
        <el-input v-model="formSearch.name" placeholder="请输入检查项名称"></el-input>
      </el-form-item>

      <el-form-item size="small">
        <el-button  v-if="$root.btnControl.find(item=>item=='view')" @click="getlist">查 询</el-button>
      </el-form-item>

      <el-form-item size="small">
        <el-button size="small" v-if="$root.btnControl.find(item=>item=='add')" @click="addDialog=true"><i class="el-icon-plus"></i> 新 增</el-button>
      </el-form-item>
      <el-form-item size="small">
        <!-- v-if="$root.btnControl.find(item=>item=='delete')" -->
        <el-button size="small" v-if="$root.btnControl.find(item=>item=='delete')" type="danger" @click="deleInfor(false)">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="formData" style="width: 100%" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="orgName" label="所属组织架构"></el-table-column>
      <el-table-column prop="projectName" label="所属项目"></el-table-column>
      <el-table-column prop="name" label="检查项名称"></el-table-column>
      <el-table-column label="是否多选">
        <template slot-scope="scope">
          {{scope.row.choose==1?"是":'否'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width=310>
        <template slot-scope="scope">
          <!-- v-if="$root.btnControl.find(item=>item=='edit')" -->
          <el-button type="warning" size="small"  @click="backfill(scope.row,2)">修 改</el-button>
          <!-- v-if="$root.btnControl.find(item=>item=='delete')" -->
          <el-button type="danger" size="small"  @click="deleInfor(scope.row.id)">删 除</el-button>
          <!-- v-if="$root.btnControl.find(item=>item=='view')" -->
          <el-button type="" size="small"  @click="backfill(scope.row,3)">详 情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <paging @changePage=handleCurrentPage :get-total='total'></paging>

    <!-- 添加 -->
    <el-dialog :title="isAddorUpdate==1?'新增':isAddorUpdate==2?'修改':'详情'" @closed="canceladd" :visible.sync="addDialog" 
      :close-on-click-modal="false">
      <div class="cont_box_right">
        <el-form label-position="right" label-width="110px" :model="formPush" ref='addList'>
          <el-form-item label="选择所属组织" size="small" :rules="{
            required: true, message: '组织不能为空', trigger: 'blur'
        }">
            <el-cascader ref="cascader1" v-model="option2" :options="dataTree" :props="defaultProps2"
              @change="zuzhiChange1" clearable>
            </el-cascader>
          </el-form-item>
          <el-form-item label="选择项目" size="small" prop="projectId" :rules="{
            required: true, message: '项目不能为空', trigger: 'blur'
        }">
            <el-select v-model="formPush.projectId" placeholder="请选择项目">
              <el-option v-for="(item,index) in xqTree1" :label="item.name" :value="item.id" :key="index"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="检查项名称" size="small" prop="name" :rules="{
                required: true, message: '检查项名称不能为空', trigger: 'blur'
            }">
            <el-input v-model="formPush.name"></el-input>
          </el-form-item>

          <div v-for="(item,index) in formPush.seeds" :key="index">
            <el-form-item label="检查项内容" size="small" :prop="'seeds.'+index+'.name'" :rules="{
                  required: true, message: '检查项内容不能为空', trigger: 'blur'
              } ">
              <el-input type="text" v-model.trim="item.name" placeholder="请逐条输入检查项内容"></el-input>
              <el-button @click="deleteItem(item, index)" size="small" icon="el-icon-delete" circle></el-button>
            </el-form-item>

          </div>
          <div style="margin:20px 40px;">
            <el-button @click="addseedsname"><i class="el-icon-plus"></i> 增加检查项内容</el-button>
          </div>

          <el-form-item label="是否多选" prop="choose" :rules="{
              required: true, message: '该项不能为空', trigger: 'blur'
          }">
            <el-radio v-model="formPush.choose" :label="0">否</el-radio>
            <el-radio v-model="formPush.choose" :label="1">是</el-radio>
          </el-form-item>
          <div class="zhuyi">
            <p>注意：对于组织架构、项目的选择：</p>
            <p>1、只选择组织架构、不选择项目：默认该检查项可应用于该组织架构下的所有项目</p>
            <p>2、注意：对于组织架构、项目的选择：该检查项仅用于该项目</p>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium " @click="addDialog = false">取 消</el-button>
        <el-button size="medium " v-if="isAddorUpdate != 3 " @click="addList('addList')">提 交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
  import paging from "../paging"
  //   import paging1 from "../paging"
  import { updPatrolExamine,deletePatrolExamine, getPatrolExamineList, addPatrolExamine, xqSelectList, orgTree } from '../../url/api';
  export default {
    data() {
      return {
        option1: [],
        option2: [],
        xqTree: [],
        xqTree1: [],
        isAddorUpdate: 1,//1添加、2修改
        formSearch: {
          current: 1,
          size: 10,
          type: 1,
        },
        formSearch1: {
          type: 1,
        },
        formData: [],//数据
        deleBatch: [],//删除数据
        total: 0,//数据总数
        addDialog: false,
        formPush: {
          seeds: [{
            name: ''
          }],
          choose: 1,
          type: 1
        },
        dataTree: [],
        defaultProps: {//树状图key定义
          children: 'data',
          label: 'name'
        },
        defaultProps2: {
          children: 'children',
          label: 'name',
          value: 'id',
          expandTrigger: 'hover', checkStrictly: true
        },
      }
    },
    methods: {
      deleInfor(ids) {

        let arrId = []
        if (ids) {
          arrId.push(ids)
        } else {
          if (this.deleBatch.length != 0) {
            this.deleBatch.filter((item) => {
              arrId.push(item.id)
              return item
            })
          } else {
            this.$message("请勾选要删除的数据！")
            return
          }
        }
        this.$confirm("确定要删除吗？", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deletePatrolExamine(arrId).then((res) => {
            //console.log("删除", res)
            if (res.data.ok) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.getlist()
            } else {
              this.$message('删除失败')
            }
          })

        })
      },

      getlist() {
        console.log("this.formSearch", this.formSearch);
        getPatrolExamineList(this.formSearch).then((res) => {//查询检查项列表
          console.log("检查项列表", res)
          if (res.data.ok) {
            this.formData = res.data.data.records.filter((item) => {
              return item
            })
            this.total = res.data.data.total
          } else {
            this.$message(res.data.msg);
          }
        })
      },
      getInit() {
        // this.getshiwuTypejieshu()
        this.getlist()
        // this.getworkOrderlist()
        xqSelectList({}).then((res) => {//项目选择列表
          console.log(res)
          if (res.data.ok) {
            this.xqTree = res.data.data
          }
        })
        let org_tree = {
          name: '',
          status: 1
        }
        orgTree(org_tree).then((res) => {//获取组织列表
          console.log(res)
          if (res.data.ok) {
            this.dataTree = res.data.data
          }
        })
      },
      handleChange(value) {
        if (value.length != 0) {
          console.log(value)
          this.formSearch.orgId = this.$refs.cascader.getCheckedNodes()[0].data.id
        } else {
          this.formSearch.orgId = ''
        }
      },
      zuzhiChange1(value) {//改变组织
        if (value.length != 0) {
          console.log(value)
          this.formPush.orgId = this.$refs.cascader1.getCheckedNodes()[0].data.id
        } else {
          this.formPush.orgId = ''
        }
        let org_tree1 = {
          orgId: this.formPush.orgId
        }
        xqSelectList(org_tree1).then((res) => {//项目选择列表
          console.log(res)
          if (res.data.ok) {
            this.xqTree1 = res.data.data
            //   if(this.xqTree.length!=0){
            //     this.formPush.projectId = this.xqTree[0].id
            //   }
          }
        })
      },
      handleSelectionChange(val, self) {//多选
        this.deleBatch = val
        console.log(this.deleBatch)
      },

      backfill(row, index) {
        this.isAddorUpdate = index
        this.formPush.orgId = row.orgId;
        this.formPush.projectId = row.projectId;
        this.formPush.name = row.name;
        this.formPush.seeds = []
        this.formPush.remark = row.remark
        this.formPush.choose = row.choose
        this.formPush.id = row.id
        console.log(row);
        // let arry = row.content.split('_')
        row.seeds.forEach(val => {
          let seedsname = {
            name: ''
          }
          seedsname.name = val.name
          this.formPush.seeds.push(seedsname)
          //console.log(seedsname);
        })

        console.log(this.formPush.seeds);

        let treeDef = this.get_OrganizationId2(
          this.formPush.orgId,
          this.dataTree,
          "cascader1"
        );
        this.option2 = treeDef;
        let org_tree1 = {
          orgId: this.formPush.orgId
        }
        xqSelectList(org_tree1).then((res) => {//项目选择列表
          //console.log(res)
          if (res.data.ok) {
            this.xqTree1 = res.data.data
            //   if(this.xqTree.length!=0){
            //     this.formPush.projectId = this.xqTree[0].id
            //   }
          }
        })
        this.addDialog = true
      },



      //新增检查项
      addList(addList) {//添加/修改
        // if(this.formSearch1.projectId){
        // this.formPush.projectId = this.formSearch1.projectId
        // }
        if (!this.formPush.projectId && !this.formPush.orgId) {
          this.$message("组织与项目至少选择一项!")
          return
        }

        console.log("this.formPush", this.formPush)
        this.$refs.addList.validate((valid) => {
          console.log("valid", valid)
          if (valid) {
            this.$confirm("确定要执行此操作吗？", '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {

              //this.addDialog = false
              //console.log(this.formPush)
              if (this.isAddorUpdate == 1) {
                addPatrolExamine(this.formPush).then((res) => {
                  //console.log("新增", res)
                  if (res.data.ok) {
                    this.$message({
                      message: '添加成功',
                      type: 'success'
                    });
                    this.getlist()
                  } else {
                    this.$message('添加失败')
                  }
                })
                this.addDialog = false
              }else if(this.isAddorUpdate == 2){
                updPatrolExamine(this.formPush).then((res) => {
                  if (res.data.ok) {
                    this.$message({
                      message: '修改成功',
                      type: 'success'
                    });
                    this.getlist()
                  } else {
                    this.$message('修改失败')
                  }
                })
                this.addDialog = false
              }


            })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //取消新增
      canceladd() {
        this.option2 =[]
        this.isAddorUpdate = 1
        this.formPush = {
          seeds: [{
            name: ''
          }],
          choose: 1,
          type: 1
        };
        console.log("hahahah");
      },

      addseedsname() {
        this.formPush.seeds.push({
          name: '',
        });
      },
      deleteItem(item, index) {
        this.formPush.seeds.splice(index, 1);
        // console.log(this.formfzsh,'删除')
      },

      handleCurrentPage(val) {//页码改变
        this.formSearch.current = val
        this.getlist()
      },

      //----cascader标签回填方法封装----
      get_OrganizationId2(ids, treeData, refsName) {
        var _this = this;
        /* 
          ids 后端返回单选或者多选 的id数组(单选：string,多选为：array)
          treeData 整个树状数据
          refsName 级联组件ref值
         */
        //console.log(refsName);
        let checkdeType = false; //取 多选true 单选false
        let ValueName = "id"; //取 value 字段
        let childrenName = "children"; //取 children 字段
        let newModel = []; //赋值默认选中数组
        let itemIds = []; //单条id 回显数组
        let returnActive = false; //是否找着对应部门（数据返回单个）
        let lastRow = lastVerify(treeData); //获取最后遍历的id
        if (!checkdeType && !(ids instanceof Array)) ids = [ids]; // 单选 ids 格式转换
        for (let i = 0; i < ids.length; i++) {
          itemIds = [];
          returnActive = false;
          filterChild(ids[i], [], treeData);
          if (itemIds.length > 0) {
            if (checkdeType) {
              //多选
              newModel.push(itemIds);
            } else {
              //单选
              newModel = itemIds;
            }
          }
        }
        /* 数据过滤解释 回显数据绑定 */
        // this.$nextTick(() => {
        //     this.dataForm.defDeptIds = newModel;
        // });
        return newModel;
        /* 过滤子级 */
        function filterChild(id, parentIds, selfArr) {
          for (let j = 0; j < selfArr.length; j++) {
            if (returnActive) return false;
            returnActive = selfArr[j][ValueName] == id;
            if (returnActive) {
              parentIds.push(selfArr[j][ValueName]);
              itemIds = parentIds;
              return false;
            } else if (
              selfArr[j][childrenName] &&
              selfArr[j][childrenName].length > 0
            ) {
              parentIds.push(selfArr[j][ValueName]);
              filterChild(id, parentIds, selfArr[j][childrenName]);
            } else {
              /* 最后一级的最后一个判断 */
              if (lastRow && selfArr[j][ValueName] == lastRow) {
                //console.log("未找到对应部门!", id);
                parentIds = [];
                itemIds = parentIds;
                return false;
              }
            }
            /* 循环结束 未找着父级 */
            if (j == selfArr.length - 1 && !returnActive) {
              parentIds.splice(parentIds.length - 1, 1);
            }
          }
        }

        /* 是否最子级判断 */
        function lastVerify(allTreeData = treeData) {
          if (allTreeData && allTreeData.length > 0) {
            if (
              allTreeData[allTreeData.length - 1][childrenName] &&
              allTreeData[allTreeData.length - 1][childrenName].length > 0
            ) {
              return lastVerify(allTreeData[allTreeData.length - 1][childrenName]);
            } else {
              return lastVerify(allTreeData[allTreeData.length - 1]);
            }
          } else {
            if (allTreeData[ValueName]) return allTreeData[ValueName];
            return false;
          }
        }
      },
      //----cascader标签回填方法封装end----
    },
    mounted() {
      this.getInit()
    },
    components: {
      paging,
      //   paging1
    }
  }
</script>
<style scoped>
  .zhuyi {
    color: rgb(37, 36, 36);
    font-size: 12px;
    margin: 30px 20px;
  }
</style>